package DBLayer;
import ModelLayer.*;

import java.sql.*;
import java.util.ArrayList;


public class DBEquipment implements IFDBGeneric<Equipment>{
    private  Connection con;
   
    public DBEquipment() {
      con = DbConnection.getInstance().getDBcon();
    }
    

    public ArrayList<Equipment> getAll(){
        return miscWhere("");
    }
    
    public Equipment find(String name){  
        return singleWhere("name = '"+name);
    }
    
    public Equipment find_byID(int Prid){  
        return singleWhere("Prid = '"+Prid);
    }
   
    
    public int insert(Equipment eq) throws Exception
    {  
  
       int rc = -1;
	   String query="INSERT INTO Product(name, PurchasePrice, SalesPrice, RentPrice, CountryOfOrigin, CurrentStock, MinStock, Sid)  VALUES('"+
	  		eq.getName()  + "',"  +
		    eq.getPurchasePrice()  + ","  +
            eq.getSalesPrice() + "," +
            eq.getRentPrice() + ",'" +
            eq.getCountryOfOrigin() + "',"+ eq.getCurrentStock() + ","+ eq.getMinStock() + ","+eq.getSid() + ")" ;
	   
	   		


      try{
          Statement stmt = con.createStatement();
          stmt.setQueryTimeout(5);
     	  rc = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
     	  ResultSet rs = stmt.getGeneratedKeys();
     	  if (rs.next()) rc = rs.getInt(1);
     	
     			  
     	String query1 = "INSERT INTO Equipment(Prid, type, description) VALUES("+rc+","
     			+ " '"+eq.getType()+"','"+eq.getDescription()+"')";
     	stmt.executeUpdate(query1);
          stmt.close();
      }
       catch(SQLException ex){
          System.err.println("Could not insert Equipment obj with name "+eq.getName());
       }
       return(rc);
    }

    
	public int update(Equipment eq)
	{
		Equipment eqObj  = eq;
		int rc=-1;

		String query="UPDATE Product SET "+
		 	  "name ='"+ eqObj.getName()+"', "+
		 	  "purchasePrice ="+ eqObj.getPurchasePrice() + ", " +
              "salesPrice ="+ eqObj.getSalesPrice() + ", " +
              "rentPrice ="+ eqObj.getRentPrice() + ", " +
              "countryOfOrigin ='"+ eqObj.getCountryOfOrigin() + "', " +
              "currentStock ="+ eqObj.getCurrentStock() + ", " +
              "minStock ="+ eqObj.getMinStock() + " " +
		          " WHERE Prid = "+ eqObj.getPrid() + ""; 
  		try{ 
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		System.out.println(query);
	 	 	rc = stmt.executeUpdate(query);
	 	 	
	 	String query1="UPDATE Equipment SET "+
	 			"type ='"+ eqObj.getType()+"',"+
	 			"size = '"+ eqObj.getDescription()+"' "+
	 				"WHERE Prid = "+eqObj.getPrid() + "";
	 		stmt.executeUpdate(query1);
	 	 	
	 	 	
	 	 	

	 	 	stmt.close();
		}
	 	catch(Exception ex){
	 	 	System.out.println("Update exception in Equipment db: "+ex);
	  	}
		return(rc);
	}
	
	
	public int delete(int Prid)
	{
        int rc=-1;
	  
	  	String query="DELETE FROM product WHERE Prid = '" +Prid + "'";
       
	  	try{ 
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 	  	rc = stmt.executeUpdate(query);
	 	  	stmt.close();
  		}
   	        catch(Exception ex){
	 	  	System.out.println("Delete exception in Equipment db: "+ex);
   	        }
		return(rc);
	}
	

	 
	private ArrayList<Equipment> miscWhere(String wClause)
	{
            ResultSet results;
	    ArrayList<Equipment> list = new ArrayList<Equipment>();	
		
	    String query =  buildQuery(wClause);
  
            try{ // read the product from the database
		Statement stmt = con.createStatement();
	 	stmt.setQueryTimeout(5);
	 	results = stmt.executeQuery(query);
	 	
	
		while( results.next() ){
			Equipment eqObj = new Equipment();
	     	 eqObj = buildEquipment(results);	
                 list.add(eqObj);	
		}
   
			
		}
	 	catch(Exception e){
	 		System.out.println("Query exception - select: "+e);
	 	}
		return list;
	}
	
	//Singelwhere is used when we only select one product 	
	private Equipment singleWhere(String wClause)
	{
		ResultSet results;
		Equipment eqObj = new Equipment();
                
	        String query =  buildQuery(wClause);
		try{ // read the product from the database
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);
	 		
	 		if( results.next() ){
                            eqObj = buildEquipment(results);
                            //assocaition is to be build
                            stmt.close();
                           
			}
                        else{ //no product was found
                            eqObj = null;
                        }
		}//end try	
	 	catch(Exception e){
	 		System.out.println("Query exception: "+e);
	 	}
		return eqObj;
	}
	
	private String buildQuery(String wClause)
	{
	    String query="SELECT Prid, name, purchasePrice,SalesPrice, rentPrice, CountryOfOrigin,currentStock, minStock, Sid, type, description FROM Clothing c, Product p WHERE c.Prid=p.Prid";
		
		if (wClause.length()>0)
			query=query+" AND "+ wClause;
			
		return query;
	}
	
	private Equipment buildEquipment(ResultSet results)
      {   Equipment eqObj = new Equipment();
          try{ // the columns from the table product  are used
        	  	eqObj.setPrid(results.getInt("Prid"));
                eqObj.setName(results.getString("name"));
                eqObj.setPurchasePrice(results.getDouble("purchasePrice"));
                eqObj.setSalesPrice(results.getDouble("salesPrice"));
                eqObj.setRentPrice(results.getDouble("rentPrice"));
                eqObj.setCountryOfOrigin(results.getString("CountryOfOrigin"));
                eqObj.setCurrentStock(results.getInt("currentStock"));
                eqObj.setMinStock(results.getInt("minStock"));
                eqObj.setSid(results.getInt("Sid"));
                eqObj.setType(results.getString("type"));
                eqObj.setDescription(results.getString("description"));

          }
         catch(Exception e)
         {
             System.out.println("error in building the Equipment object");
         }
         return eqObj;
      }

 
}  
    

